import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import {
  DriverSelect,
  GroupTreeSelect,
  LineSelect,
  VehicleSelect,
} from '@/components/CustomForm';
import request from '@/utils/request';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, Space, message } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import Save from './components/Save';
const { RangePicker } = DatePicker;

const getList = async (params) => {
  const { planDate, ...others } = params;
  const res = await request({
    url: '/datas/vehicle/plan/list',
    method: 'GET',
    custom: true,
    params: {
      ...others,
      fromTime: params.planDate?.[0]
        ? dayjs(params.planDate[0]).format('YYYY-MM-DD')
        : '',
      toTime: params.planDate?.[1]
        ? dayjs(params.planDate[1]).format('YYYY-MM-DD')
        : '',
    },
  });
  return {
    total: res?.total,
    data: res?.data,
  };
};

const Index = () => {
  const [mode, setMode] = useState('list');
  const [record, setRecord] = useState();
  const [selectedKeys, setSelectedKeys] = useState([]);
  const crudRef = useRef();

  const deleteRow = (id) => {
    const ids = id ? [id] : selectedKeys;
    Modal.confirm({
      title: `确认删除所选数据?`,
      onOk: async () => {
        await request({
          url: '/datas/vehicle/plan/delete',
          method: 'POST',
          data: { ids },
        });
        message.success('操作成功');
        crudRef.current?.reload();
        setSelectedKeys([]);
      },
    });
  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '组织',
      dataIndex: 'groupName',
      fixed: 'left',
      width: 210,
      render: (text) => text || '', // 如果字段不存在则显示空字符串
    },
    {
      title: '车牌号',
      dataIndex: 'license',
      fixed: 'left',
      width: 120,
      render: (text) => text || '',
    },
    {
      title: '车牌颜色',
      dataIndex: 'plateColor',
      width: 90,
      render: (text) => {
        if (!text) return '';
        const colorMap = {
          1: '蓝色',
          2: '黄色',
          3: '黑色',
          4: '白色',
          5: '绿色',
          6: '红色',
        };
        return colorMap[text] || '';
      },
    },
    {
      title: '姓名',
      dataIndex: 'realname',
      width: 170,
      render: (text) => text || '',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 130,
      render: (text) => text || '',
    },
    {
      title: '计划线路',
      dataIndex: 'lineName',
      width: 280,
      render: (text) => text || '',
    },
    {
      title: '计划日期',
      dataIndex: 'planDate',
      width: 120,
      render: (text) => (text ? dayjs(text).format('YYYY-MM-DD') : ''),
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 90,
      render: (text) => {
        if (text === undefined || text === null) return '';
        return text === 0 ? '未执行' : '已执行';
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
      render: (text) => text || '',
    },
    {
      title: '系统时间',
      dataIndex: 'time',
      width: 180,
      render: (text) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 140,
      render: (text) => text || '',
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'operate',
      fixed: 'right',
      width: 80,
      render: (text, record) => {
        return (
          <Space>
            {/* <a
              onClick={() => {
                setRecord(record);
                setMode('edit');
              }}
            >
              编辑
            </a> */}
            <a
              onClick={() => {
                deleteRow(record.vehiclePlanId);
              }}
            >
              删除
            </a>
          </Space>
        );
      },
    },
  ];

  const fields = [
    {
      label: '组织',
      name: 'groupId',
      children: <GroupTreeSelect />,
    },
    {
      label: '车牌号',
      name: 'vehicleId',
      children: <VehicleSelect />,
    },
    {
      label: '司机',
      name: 'driverId',
      children: <DriverSelect />,
    },
    {
      label: '计划线路',
      name: 'lineId',
      children: <LineSelect />,
    },
    {
      label: '计划日期',
      name: 'planDate',
      children: <RangePicker placeholder={['开始日期', '结束日期']} />,
    },
  ];

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="vehiclePlanId"
        queryFormProps={{
          labelCol: 5,
          fieldWidth: 320,
          initialValues: {
            planDate: [dayjs(), dayjs().add(1, 'day')],
          },
        }}
        fields={fields}
        columns={columns}
        request={getList}
        toolbar={
          <>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setMode('create')}
            >
              新增
            </Button>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedKeys.length === 0}
              onClick={() => deleteRow()}
            >
              批量删除
            </Button>
          </>
        }
        tableProps={{
          rowSelection: {
            selectedRowKeys: selectedKeys,
            onChange: (selectedRowKeys) => {
              setSelectedKeys(selectedRowKeys);
            },
          },
        }}
      />
      <Save
        open={mode === 'create'}
        record={record}
        onCancel={() => {
          setRecord();
          setMode('list');
        }}
        onOk={() => {
          setRecord();
          setMode('list');
          crudRef.current?.reload();
        }}
      />
    </>
  );
};

export default Index;
